﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TomNet.IMSC.Core.Contracts.Common;
using TomNet.IMSC.Core.Contracts.NewHouse;
using TomNet.IMSC.Core.Contracts.Organization;
using TomNet.IMSC.Model.DbModels.NewHouse;
using TomNet.Web.Mvc;
using TomNet.Web.Mvc.UI;

namespace TomNet.IMSC.Web.Areas.NewHouse.Controllers
{
    [Description("管理-职业顾问")]
    public class PropertyConsultantController : BaseController
    {
        public IPropertyConsultantContract PropertyConsultantContract { get; set; }   
        public IBuildingsContract BuildingsContract { get; set; }
        public IStaffContract StaffContract { get; set; }
        public IDictionaryContract DictionaryContract { get; set; }
        #region 置业顾问列表
        [Description("管理-置业顾问列表")]
        // GET: NewHouse/PropertyConsultant
        public ActionResult Index(int BuildingID)
        {
            ViewBag.BuildingID = BuildingID;
            return View();
        }

        public ActionResult IndexAsync(int pageIndex, int pageSize,int BuildingID, string search = "")
        {
            var query = from ppt in PropertyConsultantContract.Entities
                        where !ppt.IsDeleted
                        select new
                        {
                            Id = ppt.Id,
                            BuildingID = (from b in BuildingsContract.TrackEntities where ppt.BuildingID == b.Id select b.Name).FirstOrDefault(),
                            Name = ppt.Name,
                            Sex = ppt.Sex == 0 ? "男" : "女",
                            Phone = ppt.Phone,
                            Duties = ppt.Duties,
                            CreateStaffID = (from staff in StaffContract.TrackEntities where ppt.CreateStaffID == staff.Id select staff.Name).FirstOrDefault(),

                            IsDelete = ppt.IsDeleted,
                            CreatedTime = ppt.CreatedTime
                        };

            //数据总数
            var total = query.Count();

            //默认给一个排序的字段
            query = query.OrderByDescending(m => m.Id);

            //分页(假如total == 0，则取消分页查询，提高性能)
            query = total > 0 ? query.Skip((pageIndex - 1) * pageSize).Take(pageSize)
                : query;

            //此处可以采用匿名对象 GridData<object>
            GridData<object> gridData = new GridData<object>() { Total = total, Rows = query.ToList() };

            //此处采用重写后的jsonResult
            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        }
        #endregion

        #region 置业顾问添加
        [Description("管理-置业顾问添加")]
        public ActionResult Insert(string BuildingID)
        {
            ViewBag.BuildingID = BuildingID;
            return View();
        }
        [HttpPost]
        public ActionResult InsertAsync(PropertyConsultant entity)
        {
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();

            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            entity.CreateStaffID = model.AgentId; 
            entity.ShowIndex = 0;
            try
            {
                var count = PropertyConsultantContract.Insert(entity);
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "录入成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "录入失败";
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 置业顾问修改
        [Description("管理-置业顾问修改")]
        public ActionResult Edit(int id,string BuildingID)
        { 
            var pentity = PropertyConsultantContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (pentity == null) throw new Exception("未找到该实体");
            ViewData["pentity"] = pentity;
            ViewBag.BuildingID = BuildingID;
            return View();
        }
        [HttpPost]
        public ActionResult EditAsync(PropertyConsultant entity)
        {
            var result = new AjaxResult();
            var cookies = Common.CookiesManagement.GetCookies();
            var ticket = Common.CookiesManagement.GetTicket(cookies);
            var model = Common.CookiesManagement.GetLoginModel(ticket);
            entity.CreateStaffID = model.AgentId;
            entity.ShowIndex = 0;
            try
            { 
                var count = PropertyConsultantContract.Update(entity);
                if (count > 0)
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "修改成功";
                }
                else
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "修改失败";
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 置业顾问删除
        [Description("管理-置业顾问删除")]
        [HttpPost]
        public ActionResult DeleteAsync(string ids)
        {
            var result = new AjaxResult();
            try
            {
                string[] idsStr = ids.Split(new char[] { ',' });
                int[] idsInt = Array.ConvertAll(idsStr, id => Convert.ToInt32(id));
                PropertyConsultantContract.UpdateDirect(m => idsInt.Contains(m.Id), m => new PropertyConsultant { IsDeleted = true });

                result.Type = AjaxResultType.Success;
                result.Content = "删除成功";
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion 
    }
}